<?php

namespace app\model;

use think\facade\Db;
use think\Model;

class BookChaptersModel extends Model {

    protected $table ="book_chapters";

    protected $pk = 'chapter_id';

    private $cacheKey="chapter:id:";

    private $cacheTime=5184000;


    /*
         * 获取total
         * */
    public function getTotal($where=[]){
        return Db::name($this->table)->where($where)->count();
    }


    /*
     * 获取list
     * */
    public function getList($where=[],$page = null,$limit = null,$orderField = null,$orderType = "ASC"){

        $obj =  Db::name($this->table)->field($this->pk)->where($where);

        if(!empty($page) && !empty($limit)){
            $obj = $obj->page($page, $limit);
        }

        if(!empty($orderField) && !empty($orderType)){
            $obj = $obj->order($orderField, $orderType);
        }

        $list = $obj->select();

        if($list){
            $return = [];
            foreach($list as $item){
                $return[] = $this->getInfo($item[$this->pk]);
            }
            return $this->buildTree($return);
        }
        return [];
    }



    /*
   * 获取订单状态详情
   * */
    public function getInfo($id){
        $cacheKey = $this->cacheKey.$id;
        $redisModel = new RedisModel();
        $info = $redisModel->get($cacheKey);
        if($info){
            return json_decode($info,true);
        }

        $info = Db::name($this->table)->find($id);

        if($info){
            $redisModel->set($cacheKey,json_encode($info,256),$this->cacheTime);
            return $info;
        }
        return $info;
    }




    /*
* 更新条件更新订单
* */
    public function addOne($data){
        return Db::name($this->table)->insertGetId($data);
    }




    /*
 * 更新条件更新订单
 * */
    public function updateAll($where,$data){
        return Db::name($this->table)->where($where)->update($data);
    }




   private function buildTree(array $elements, int $parentId = 0): array {
        $branch = [];

        foreach ($elements as $element) {
            if ($element['parent_id'] == $parentId) {
                $children = $this->buildTree($elements, $element['chapter_id']);
                if ($children) {
                    $element['children'] = $children;
                }
                $branch[] = $element;
            }
        }

        return $branch;
    }


}